package com.api.smoke.department;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import org.springframework.test.context.ContextConfiguration;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.api.test.AbstractApiTest;
import com.api.test.VoidContextLoader;
import com.api.util.repo.DtoFactory;
import com.api.util.repo.impl.Domain;
import com.api.util.repo.impl.DomainUser;
import com.api.util.repo.impl.ZyncroRepo;
import com.util.zyncroweb.DomainProperty;
import com.util.zyncroweb.EnterpriseProperty;
import com.zyncro.api.IDepartmentApiService;
import com.zyncro.api.exceptions.ZyncroApiException;
import com.zyncro.api.model.ObjectResultApi;
import com.zyncro.api.model.UploadDocumentResultApi;

@ContextConfiguration(loader = VoidContextLoader.class)
public class UploadDepartmentSmoke extends AbstractApiTest {

	private String departmentUrn;

	@BeforeClass
	protected void setUp() throws Exception {

		final ZyncroRepo zyncroRepo = getRepo();
		final String domainName = this.getClass().getSimpleName();
		final DomainUser mainAdmin = zyncroRepo.getMainUser(domainName);

		getApi().login(mainAdmin.getAppId(), mainAdmin.getPassword());

		this.departmentUrn = zyncroRepo.getPropertyDto(domainName, new DtoFactory<String>() {

			public String createDto() {

				Domain domain = zyncroRepo.getDomain(domainName);
				getZyncroWebApi().login(mainAdmin.getAppId(), mainAdmin.getPassword());

				getZyncroWebApi().editDomainProperty(domain.getDomainUrn(), DomainProperty.ENTERPRISES, EnterpriseProperty.DEPARTMENT);

				try {
					ObjectResultApi<String> result = getApi().getService(IDepartmentApiService.class).createDepartment("nombre",
							"description", "address", "telephone", "email", "web", "fax", true, null, null, false);

					return result.getObject();

				} catch (Exception e) {

					throw new IllegalStateException("Exception creating GetDepartments test data", e);
				}
			}
		});
	}

	@Test
	public void testUpload() throws ZyncroApiException, FileNotFoundException {
		File file = new File("pom.xml");
		String fileName = file.getName();
		Long length = file.length();

		FileInputStream inputStream = new FileInputStream(file);

		String parentDocumentUrn = null;

		String iddocument = null;
		String description = null;

		ObjectResultApi<UploadDocumentResultApi> result = getApi().getService(IDepartmentApiService.class).upload(departmentUrn,
				getApi().getAccessKey(), parentDocumentUrn, iddocument, description, fileName, length, inputStream);

		UploadDocumentResultApi documentResult = result.getObject();
		Assert.assertNotNull(documentResult);

		Assert.assertEquals(documentResult.getName(), fileName);
		Assert.assertEquals(Long.valueOf(documentResult.getSize()), length);
		Assert.assertEquals(documentResult.getGroupUrn(), this.departmentUrn);
	}
}
